const express = require('express'),
    router = express.Router(),
    article = require("../model/article"),
    util = require("../util/util"),
    moment = require('moment');


/**
 * @function 增加文章
 * @author yelin
 * @date 2018-05-25
 * @param artid,arttype,arttitle,shorttitle,source,,keyword,summay,content,author,sortid,deliver,showflag,audit,delivertime
 */
router.post('/add', (req, res) => {
    const newObj = new article(req.body);
    newObj.arttype=req.body.arttype;
    newObj.keyword=req.body.keyword;
    newObj.sortid=req.body.sortid;
    newObj.deliver=req.body.deliver;
    newObj.audit=req.body.audit;
    newObj.showflag=req.body.showflag;
    let delivertime;
    if (newObj.deliver === "1") {
        delivertime = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
    } else {
        delivertime = null
    }
    let findparams={
        artid:req.body.artid
    }
    if(req.body.arttitle){
        article.find(findparams, (err,results)=> {
            if(err){
                res.send(util.reObj(-1,'failed',err))
            }else {
                if(results.length>0){
                    res.send(util.reObj(-2,'exist'))
                }else{
                    newObj.save( (err, result)=>{
                        if(err){
                            res.send(util.reObj(-1,'add  failed'))
                        }else{
                            res.send(util.reObj(0,'add  success',result))
                        }
                    })
                }
            }
        })
    }else{
        res.send(util.reObj(-1,'标题不能为空'))
    }
})

/**
 * @function 修改文章
 * @author yelin
 * @date 2017-05-26
 * @param artid,arttype,arttitle,shorttitle,source,,keyword,summay,content,author,sortid,deliver,showflag,delivertime,audit
 */
router.post('/edit', (req, res) => {
    let artid = req.body.artid
    let arttype = req.body.arttype.join(',') || ' '
    let arttitle = req.body.arttitle || ''
    let shorttitle = req.body.shorttitle || ''
    let source = req.body.source || ''
    let keyword = req.body.keyword.join(',') || ' '
    let summay = req.body.summay || ''
    let content = req.body.content || ''
    let author = req.body.author || ''
    let sortid = req.body.sortid || ''
    let deliver = req.body.deliver || ''
    let delivertime = req.body.delivertime
    if(deliver==1&&!delivertime){
        delivertime = moment(Date.now()).format('YYYY-MM-DD HH:mm:ss')
    }else {
        delivertime = null
    }
    let audit = req.body.audit || ''
    let showflag = req.body.showflag || ''
    let params = {
        artid: artid
    }
    let updateparams = {
        artid: artid,
        arttype: arttype,
        arttitle: arttitle,
        shorttitle: shorttitle,
        source: source,
        keyword: keyword,
        summay: summay,
        content: content,
        author: author,
        sortid: sortid,
        deliver: deliver,
        delivertime: delivertime,
        audit: audit,
        showflag: showflag
    }

    //去掉空的属性
    for (var key of Object.keys(updateparams)) {
        if (!updateparams[key])
            delete updateparams[key]
    }

    if (artid.length > 30 || arttitle.length > 50 || shorttitle.length > 50 || keyword.length > 30 || source.length > 30 || author.length > 30 || sortid.length > 4 || deliver.length > 1 || audit.length > 1 || showflag.length > 1) {
        res.send(util.reObj(-1, '请求参数长度超出限制'))
    } else {
        article.findOneAndUpdate(params,updateparams,(err,results)=>{
            if(err)
            {
                res.send(util.reObj(-1,'修改失败',err))
            }
            else
            {
                res.send(util.reObj(0,'修改成功',results))
            }
        })
    }

})

/**
 * @function 批量审核文章
 * @author siwei
 * @date 2018-07-04
 * @param artid,audit
 */
router.post('/pass', (req, res) => {
    let artidArr = req.body.artid.split(',');
    let audit = req.body.audit || '1'
    let params = {
        artid: artidArr
    }
    let updateparams = {
        audit: audit
    }
    gps_article.update(updateparams, {where: params}).then(record => {
        res.send(util.reObj(0, record[0] + '篇文章审核成功', record[0]))
    }).catch(err => {
        res.send(util.reObj(-1, '文章审核失败', err))
    });
})

/**
 * @function 删除文章
 * @author yelin
 * @date 2017-05-25
 * @param artid
 */
router.post('/del', (req, res) => {
    let artid = req.body.artid
    let params = {
        artid: artid
    }
    if(artid)
    {
        article.deleteMany(params,(err,result)=>{
            if (err) {
                res.send(util.reObj(-1,'删除失败'))
            }
            else {
                if(result.deletedCount>0)
                {
                    res.send(util.reObj(0,'删除成功'))
                }
                else
                {
                    res.send(util.reObj(0,'删除失败或此记录不存在'))
                }
            }
        })
    }
    else{
        res.send(util.reObj(-1,'artid can not be null'))
    }
})

/**
 * @function 批量删除文章
 * @author siwei
 * @date 2018-07-17
 * @param artid
 */
router.post('/delmultiple', (req, res) => {
    let params = {
        artid: req.body.artid.split(',')
    }
    gps_article.destroy({where: params}).then(record => {
        if (record > 0) {
            res.send(util.reObj(0, record + '篇文章删除成功', record))
        } else {
            res.send(util.reObj(-1, '批量删除文章失败或记录不存在', record))
        }
    }).catch(err => {
        res.send(reObj(-1, '批量删除文章失败', err))
    });

})

/**
 * @function 查询文章内容(前台有同样的接口)
 * @author Wayne
 * @date 2018-07-02
 * @param artid
 */
router.post('/getArticle', (req, res) => {
    let params = {}
    let artid = req.body.artid
    params.artid = artid
    console.log("find params:"+JSON.stringify(params))
    article.find(params).then(record => {
        console.log('record:'+JSON.stringify(record))
        if (record) {
            res.send(util.reObj(0, '查询文章内容成功', record))
        } else {
            res.send(util.reObj(-1, '查询文章内容失败或此记录不存在'))
        }
    }).catch(err => {
        res.send(util.reObj(-1, '查询文章内容失败', err))
    });
})

/**
 * @function 浏览次数加1
 * @author siwei
 * @date 2018-07-06
 * @param artid
 */
router.get('/addCount', (req, res) => {
    let sequelize = DbInit.sequelize
    let artid = req.query.artid

    if (artid) {
        let sql = 'update gps_article set readcount=readcount+1 where artid="' + artid + '"';

        sequelize.query(sql).then(record => {
            res.send(util.reObj(0, '浏览次数更新成功', record))
        }).catch(err => {
            res.send(util.reObj(-1, '浏览次数更新失败', err))
        })
    } else {
        res.send(util.reObj(-1, 'artid不能为空'))
    }
})

/**
 * @function 查询符合条件的文章列表(前台也有同样的获取接口)
 * @author wayne
 * @date 2017-05-19
 * @param deliver,audit,arttype,author,showflag,keyword,pagerow,page
 */
router.post('/getArticleList', async(req, res) => {
    let  param={},
        skipnum=req.query.skipnum||0,
        pagesize=req.query.pagesize||10,
        deliver = req.body.deliver,
        audit = req.body.audit,
        arttype = req.body.arttype,
        author = req.body.author,
        showflag = req.body.showflag,
        keyword = req.body.keyword;

    if (author) {
        param.author = author
    }
    if (arttype) {
        // params.arttype = arttype
        param.arttype =  arttype
    }
    if (deliver) {
        param.deliver = deliver
    }
    if (audit) {
        param.audit = audit
    }
    if (showflag) {
        param.showflag = showflag
    }
    if (keyword) {
        param.arttitle =  keyword
    }
    console.log('params:'+JSON.stringify(param))
    try {
        const results = await article.find(param,null,{skip: parseInt(skipnum), limit:parseInt(pagesize),sort: {register_time: -1}})
        const count =await article.count(param,null,{skip: parseInt(skipnum), limit:parseInt(pagesize),sort: {register_time: -1}})
        res.send(util.reObj("0",'success',results,count))
    }
    catch (err) {
        console.log('err:'+err)
        res.send(util.reObj(-1,'failed',err))
    }

})

/**
 * @function 根据一级栏目获取所有已发布的文章数据(前台有同样的接口)
 * @author wayne
 * @date 2018-07-31
 * @param deliver,audit,arttype,showflag,pagerow,page
 */
router.post('/getArticleList_byparentid', (req, res) => {
    let params = {}
    let deliver = req.body.deliver || '1'
    let audit = req.body.audit || '1'
    let arttype = req.body.arttype
    let showflag = req.body.showflag || '1'
    let pagerow = parseInt(req.body.pagerow)
    let page = parseInt(req.body.page)
    //对页码进行容错
    if (pagerow > 999) {
        pagerow = 999
    }
    if (page == 0) {
        page = 1
    }
    if (arttype) {
        params.arttype = {'$like': arttype + '%'}
    }
    params.deliver = deliver
    params.audit = audit
    params.showflag = showflag

    gps_article.findAndCountAll({
        order: "delivertime DESC",
        limit: pagerow || 100,
        offset: parseInt(pagerow * (page - 1)) || 0,
        where: params
    }).then(record => {
        res.send(util.reObj(0, '获取文章列表成功', record.rows, record.count))
    }).catch(err => {
        res.send(util.reObj(-1, '获取文章列表失败', err))
    });
})


module.exports = router;
